
var searchResults=[];
var gFoundEngines=[];
var gSetKey=-1;
var lastSearchMethod={};
var gLastSearchXMLData;

//@TODO: Fix next-previous
var gRecordsPerPage = (function() {
    if (nsPreferences.copyUnicharPref("trucoder.plugin.records_per_page") == null) {
        return 10;
    } else {
        return parseInt(nsPreferences.copyUnicharPref("trucoder.plugin.records_per_page"));
    }
})();

var totalPages;
var gCurrentPageIndex=1;
var gStartRecordIndex;
var gEndRecordIndex;

const tabURI="chrome://footbar/content/code.html";
const DisplayDatasetURI='chrome://footbar/content/xml/display-dataset.html';

/* Sample usage
var scropeObject = new Object();
objScriptLoader.loadSubScript('chrome://footbar/content/Engines/EngineDefaultImpl.js', scropeObject);
var Engine=new scropeObject.EngineImpl();
    Engine.init();
*/

function toggleNotes(){

}

function updateSearchIcon(iconClassName){
    var menu=document.getElementById('trucoder-searchoptions-menu');
    var className=menu.className;
    var classes=className.split(' ');
    if(classes.length>1){
        classes[1]=iconClassName;
    }else{
        classes[0]+=" "+ iconClassName;
    }
    menu.className = classes.join(' ');
}

/**
 * Tobble TabView State
 */
var isTabView=false;
function switchTabViewState(){
    var codeOverlayContainer=document.getElementById('footbar-code-box');
    var codeContainer=document.getElementById('footbar-code-box-container');


    var tabViewButton=document.getElementById('footbar-tabView');
    //need to be inverse because we are getting the state befor it have been set.
    isTabView=!(tabViewButton.checked);


    //Ref: http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Getting_access_to_the_Browser
    var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
            .getInterface(Components.interfaces.nsIWebNavigation)
            .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
            .rootTreeItem
            .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
            .getInterface(Components.interfaces.nsIDOMWindow);


    var gBrowser=mainWindow.getBrowser();


    if(isTabView){
        codeOverlayContainer.setAttribute("flex","0");
        codeContainer.style.display="none";
        tabViewButton.image="/skin/tab_remove.png";

        // Add tab, then make active
        gBrowser.selectedTab = gBrowser.addTab(tabURI);
        // Focus *this* browser
        gBrowser.focus();

    }else{
        //Event handler takes care of setting the style
        //Find the  Tab and Remove it from the browser.
        var num = gBrowser.browsers.length;
        for (var i = 0; i < num; i++) {
            var b = gBrowser.getBrowserAtIndex(i);
            try {
                if(b.currentURI.spec==tabURI){
                    gBrowser.removeTab(b)
                    break;
                }
            } catch(e) {
                alert(e);
            }
        }
    }
}

/**
 * Update the search display after the data have been added to XML or deleted from XML
 */
function updateSearchDisplay(){
    searchResults=[];
    if(lastSearchMethod.method=='text'){
        parseXMLSearchResults( Footbar.Plugins.getActiveEngine().searchByText( lastSearchMethod.data ), false );

    }else{
        parseXMLSearchResults( Footbar.Plugins.getActiveEngine().searchByKeywords( lastSearchMethod.data, lastSearchMethod.type ), false );
    }
}

/**
 * Remove snippet.
 */
function deleteSnippet(){
    var snippet=searchResults[document.getElementById('search-list-tree').currentIndex];
    var ans=confirm("Are you sure you want to delete snippet:\n"+snippet.title);
    if(ans){
        Footbar.Plugins.getActiveEngine().deleteSnippet(snippet);
    }
}
function resetWatchdogSet(){
    gSetKey=-1;

    var saveButton=document.getElementById('footbar-watchdog-setname-savebutton');
    saveButton.setAttribute("label","  Add")

    var setName=document.getElementById('footbar-watchdog-setname');
    setName.value="SetName";

}

//Determine if we are updating or saving the set
function updateSaveSet(){
    if(gSetKey==-1){
        addWatchdogSet();
    }else{
        updateWatchdogSet();
    }
}

/**
 * Add new Watch dog set
 */
function addWatchdogSet(){

    var setName=document.getElementById('footbar-watchdog-setname');
    var title=setName.value;
    var setKey=Math.round(Math.random()*100000);

    var gridList=document.getElementById( 'footbar-set-tree-watchdog' );
    var	treechildren = gridList.getElementsByTagName("treechildren")[0];

    var	treeitem = document.createElement("treeitem");
    treeitem.setAttribute("container", "true");
    treeitem.setAttribute("open", "false");
    treeitem.setAttribute("setKey", setKey);
    treeitem.setAttribute("isSet", true);

    var	treerow = document.createElement("treerow");
    treerow.setAttribute("id",  "setname-treerow-"+setKey);

    var label_title= document.createElement("treecell");
    label_title.setAttribute("label",  title);

    var  sub_treechildren = document.createElement("treechildren");

    //Now we add back current selection
    var checkBoxes=document.getElementById('grid-tags-watchdog')
    var checkBoxes=checkBoxes.getElementsByTagName('checkbox');

    for(var k=0;k<checkBoxes.length;k++){
        var box=checkBoxes[k];
        if(box.checked){
            var dataObject={
                label:box.getAttribute("label"),
                key:box.getAttribute("value")
            };
            sub_treechildren.appendChild( Footbar.TreeUtil.cellNode(dataObject) );
        }
    }

    treerow.appendChild(label_title);
    treeitem.appendChild(treerow);
    treeitem.appendChild(sub_treechildren);

    treechildren.appendChild(treeitem);
    serializeTreeToXML();
}



/**
 * Write file to the user profile with the keyword sets
 * Ref : http://www.captain.at/programming/xul/
 */
function updateWatchdogSet(){

    //Update the treeDisplay

    var tree=document.getElementById('footbar-set-tree-watchdog');
    var treeBox = tree.treeBoxObject;

    var rootElements=tree.getElementsByTagName("treechildren")[0];
    var childElements=rootElements.getElementsByTagName("treeitem");

    for(var i=0;i<childElements.length;i++){
        if(!childElements[i].hasAttribute("container")){
            continue;
        }
        var rootKey=childElements[i].getAttribute('setKey');
        var containerElements=childElements[i].getElementsByTagName("treechildren")[0];
        if(rootKey==gSetKey){
            try {
                // This is one way to remove all children from a node
                while (containerElements.firstChild)
                {
                    //The list is LIVE so it will re-index each call
                    containerElements.removeChild(containerElements.firstChild);
                };
            } catch(e) {
                alert(e)
            }
            //Now we add back current selection
            var checkBoxes=document.getElementById('grid-tags-watchdog')
            var checkBoxes=checkBoxes.getElementsByTagName('checkbox');

            for(var k=0;k<checkBoxes.length;k++){
                var box=checkBoxes[k];
                if(box.checked){
                    var dataObject={
                        label:box.getAttribute("label"),
                        key:box.getAttribute("value")
                    };
                    containerElements.appendChild( Footbar.TreeUtil.cellNode(dataObject) );
                }

            }
        }
    }

    //	treeBox.rowCountChanged();
    serializeTreeToXML();
}


function serializeTreeToXML(){
    var xmlstring=[];
    var tree=document.getElementById('footbar-set-tree-watchdog');
    var rootElements=tree.getElementsByTagName("treechildren")[0];
    var childElements=rootElements.getElementsByTagName("treeitem");

    xmlstring[xmlstring.length] ='<?xml version="1.0"?>';
    xmlstring[xmlstring.length] ='<root>';
    for(var i=0;i<childElements.length;i++){
        if(childElements[i].hasAttribute("container")){
            var rootItem=childElements[i].getElementsByTagName("treecell")[0];
            var rootLabel=rootItem.getAttribute('label');
            var rootKey=childElements[i].getAttribute('setKey');
            xmlstring[xmlstring.length] = '<set name="'+rootLabel+'" key="'+rootKey+'">';
            xmlstring[xmlstring.length] ='  <keywords>';

            var containerElements=childElements[i].getElementsByTagName("treeitem");
            for(var j=0;j<containerElements.length;i++,j++){
                var childLabel=containerElements[j].getElementsByTagName("treecell")[0].getAttribute('label');
                var childKey=containerElements[j].getElementsByTagName("treecell")[0].getAttribute('key');

                xmlstring[xmlstring.length] = '  <pair value="'+childLabel+'" key="'+childKey+'"/>';

            }
            xmlstring[xmlstring.length] ='  </keywords>';
            xmlstring[xmlstring.length] ='</set>';
        }
    }
    xmlstring[xmlstring.length] ='</root>';
    writeFileData( xmlstring.join("\n" ));
}


function writeFileData(output){
    var savefile = "watchdog-sets.xml";
    savefile = Footbar.Util.findPluginPath()+savefile;

    //alert('File Writen to:'+savefile);

    var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath( savefile );
    if ( file.exists() == false ) {
        alert( "Creating file... " );
        file.create( Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 420 );
    }
    var outputStream = Components.classes["@mozilla.org/network/file-output-stream;1"].createInstance( Components.interfaces.nsIFileOutputStream );


    outputStream.init( file, 0x04 | 0x08 | 0x20, 420, 0 );
    //	var output = " I Am  a sample output data XXX";
    var result = outputStream.write( output, output.length );
    outputStream.close();
}

/**
 * Read file from the filesystem
 * @ref http://www.captain.at/programming/xul/
 * @param {Object} filename
 */
function readFile(filename){
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    } catch (e) {
        alert("Permission to read file was denied.");
    }
    var file = Components.classes["@mozilla.org/file/local;1"]
            .createInstance(Components.interfaces.nsILocalFile);
    file.initWithPath( filename );
    if ( file.exists() == false ) {
        alert("File does not exist");
    }
    var is = Components.classes["@mozilla.org/network/file-input-stream;1"]
            .createInstance( Components.interfaces.nsIFileInputStream );
    is.init( file,0x01, 00004, null);
    var sis = Components.classes["@mozilla.org/scriptableinputstream;1"]
            .createInstance( Components.interfaces.nsIScriptableInputStream );
    sis.init( is );
    var output = sis.read( sis.available() );

    return output;
}


//http://xullite.blogspot.com/
function sortTree(){
    var searchTree=document.getElementById( 'sort-col-last-visit-date' );
    //alert(searchTree);
    var sortService = Components.classes["@mozilla.org/xul/xul-sort-service;1"].getService(Components.interfaces.nsIXULSortService);
    sortService.sort(searchTree, "rdf:http://home.netscape.com/NC-rdf#LastVisitDate", "ascending" );
}



function copyCodeToClipBoard(){
    var Iframe=new codeFrame();
    var codeText=Iframe.document.getElementById('footbar-code').value;
    const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
    gClipboardHelper.copyString(codeText);
}


/**
 * Reset values before next search
 */
function reset(){
    searchResults=[];
    gIsSearchPreloaded=false;
    gStartRecordIndex=1;
    gEndRecordIndex=gRecordsPerPage;
    gCurrentPageIndex=1;
}

function doSearchKeywords(){
    reset();
    var keywords=[];
    var checkBoxes=document.getElementById('grid-tags-search')
    var checkBoxes=checkBoxes.getElementsByTagName('checkbox');
    var searchType=document.getElementById('grid-tags-search-type');

    for(var k=0;k<checkBoxes.length;k++){
        var box=checkBoxes[k];
        if(box.checked){
            keywords.push(box.getAttribute("value"));
        }
    }

    lastSearchMethod={
        method:'keyword',
        data:keywords,
        type:searchType.value
    }

    parseXMLSearchResults( Footbar.Plugins.getActiveEngine().searchByKeywords( keywords, searchType.value ), false );
}

function doSearchQuery(){
    reset();
    var searchText=document.getElementById('footbar-search-box').value;
    lastSearchMethod={
        method:'text',
        data:searchText
    }

    parseXMLSearchResults( Footbar.Plugins.getActiveEngine().searchByText( searchText ), false );
}

function recordSetNextPage(){
    var elementNext=document.getElementById('footbar-resultset-next-button');
    if(gCurrentPageIndex==totalPages){
        elementNext.setAttribute("disabled", true);
    }else if(gCurrentPageIndex<totalPages){
        elementNext.setAttribute("disabled", false);

        gCurrentPageIndex++;
    }
    parseXMLSearchResults();
}

function recordSetPreviousPage(){
    var elementPrevious=document.getElementById('footbar-resultset-previous-button');
    if(gCurrentPageIndex==1){
        elementPrevious.setAttribute("disabled", true);
    }else if(gCurrentPageIndex>1){
        elementPrevious.setAttribute("disabled", false);
        gCurrentPageIndex--;
    }
    parseXMLSearchResults();
}

function recordSetFirstPage(){
    gCurrentPageIndex=1;
    parseXMLSearchResults();
}

function recordSetLastPage(){
    gCurrentPageIndex=totalPages;
    parseXMLSearchResults();
}


var gIsSearchPreloaded=false;

/**
 * Preload the search into an arraySo we don't have to parse the file all the time
 */
function preloadSearchItems(xmldata){
    var root = xmldata.getElementsByTagName("root")[0];
    var items = root.getElementsByTagName("row");

    for (var i=0;i<items.length;i++){
        var itemrow=items[i];
        var title=itemrow.getElementsByTagName("title")[0];
        var keywords=itemrow.getElementsByTagName("keywords")[0];
        var description=itemrow.getElementsByTagName("description")[0];
        var code=itemrow.getElementsByTagName("code")[0];

        //Process keywords
        var keywordsLabel="";
        var kdelim=",";
        var keywordData=[];
        var keywordList=itemrow.getElementsByTagName("pair");
        for(var k=0;k<keywordList.length;k++){
            if(keywordList.length-1==k)kdelim="";
            keywordsLabel+=keywordList[k].getAttribute("value")+kdelim;
            keywordData[keywordData.length]={
                value:keywordList[k].getAttribute("value"),
                key:keywordList[k].getAttribute("key")
            }
        }
        var obj=new Object();
        obj={
            title:title.textContent,
            keywords:{label:keywordsLabel,data:keywordData},
            description:description.textContent,
            code:code.textContent,
            language:code.getAttribute("language"),
            read:false,
            uid:itemrow.getAttribute("uid")
        };
        searchResults[searchResults.length]=obj;

        if(!searchResults[searchResults.length]){
            //	alert("Initalization error :searchResults[searchResults.length]"+searchResults.length)
        }
    }
    gIsSearchPreloaded=true;
    //alert("data preloaded="+searchResults.length);
}

/**
 *
 * @param {Object||String} xmlObject Accespts XMLDocument or String
 */
function parseXMLSearchResults(xmlObject, cacheXML){
    var xmldata = null;
    var searchContainer=document.getElementById('footbar-search-container');
    searchContainer.style.visibility="visible";
    if(xmlObject){
        if(typeof(xmlObject)=='string'){
            xmldata = (new DOMParser()).parseFromString(xmlObject, "text/xml");
        }else{
            xmldata=xmlObject;
        }
    }else{
        xmldata=gLastSearchXMLData;
    }

    var gridList=document.getElementById( 'search-list-tree' );
    var	treechildren = gridList.getElementsByTagName("treechildren")[0];


    //Suppres Events
    Footbar.TreeUtil.suppresEvents( gridList.view.selection );
    //Prepare the tree : delete all the node from the treechildren
    var rootElements=treechildren;//tree.getElementsByTagName("treechildren")[0];
    try {
        while (rootElements.firstChild){
            rootElements.removeChild(rootElements.firstChild);
        };
    } catch(e) {
        alert(e)
    }
    //Restore suppresed events
    Footbar.TreeUtil.restoreSuppresedEvents();

    if(!gIsSearchPreloaded){
        preloadSearchItems(xmldata);
    }

    var root = xmldata.getElementsByTagName("root")[0];
    var items = root.getElementsByTagName("row");

    var reminder=0;
    totalPages=Math.round((items.length)/gRecordsPerPage);//-(items.length%gRecordsPerPage))
    gStartRecordIndex=(gCurrentPageIndex*gRecordsPerPage)-gRecordsPerPage;
    gEndRecordIndex=gCurrentPageIndex*gRecordsPerPage
    if((items.length%gRecordsPerPage)>0){
        totalPages++;
    }

    var resultsetLabel=document.getElementById('footbar-resultset-label');

    if(resultsetLabel){
        var labelValue="Page {currentPage} of {totalPages}";
        labelValue=labelValue.replace("{currentPage}", gCurrentPageIndex);
        labelValue=labelValue.replace("{totalPages}", totalPages);
        resultsetLabel.value=labelValue

    }

    var elementPrevious=document.getElementById('footbar-resultset-previous-button');
    if(gCurrentPageIndex>1){
        elementPrevious.setAttribute("disabled", false);
    }else{
        elementPrevious.setAttribute("disabled", true);
    }

    var elementNext=document.getElementById('footbar-resultset-next-button');
    if(gCurrentPageIndex<totalPages){
        elementNext.setAttribute("disabled", false);
    }else{
        elementNext.setAttribute("disabled", true);
    }

    //alert("gStartRecordIndex="+gStartRecordIndex+"\n"+"gEndRecordIndex="+gEndRecordIndex);

    //for (var i=0;i<items.length;i++){
    for (var i=gStartRecordIndex;i<gEndRecordIndex;i++){
        var itemrow=items[i];
        if(itemrow==null){
            break;
        }

        var realIndex=gStartRecordIndex+i;
        var title=itemrow.getElementsByTagName("title")[0];
        var keywords=itemrow.getElementsByTagName("keywords")[0];
        var description=itemrow.getElementsByTagName("description")[0];
        var code=itemrow.getElementsByTagName("code")[0];
        var	treeitem = document.createElement("treeitem");
        var	treerow = document.createElement("treerow");
        treerow.setAttribute("id",  "search-treerow-"+i);
        var label_title= document.createElement("treecell");
        label_title.setAttribute("label",  i+" : "+title.textContent);

        //Process keywords
        var keywordsLabel="";
        var kdelim=",";
        var keywordData=[];
        var keywordList=itemrow.getElementsByTagName("pair");
        for(var k=0;k<keywordList.length;k++){
            if(keywordList.length-1==k)kdelim="";
            keywordsLabel+=keywordList[k].getAttribute("value")+kdelim;
        }

        var label_kwid= document.createElement("treecell");
        label_kwid.setAttribute("label", keywordsLabel );

        var readFlag="unread";
        if(searchResults[i].read){
            readFlag = "read";
        }else{
            readFlag = "unread";
        }
        label_title.setAttribute("properties", readFlag);
        label_kwid.setAttribute("properties", readFlag);

        treerow.appendChild(label_title);
        treerow.appendChild(label_kwid);

        treerow.setAttribute("id", "footbar-search-list-"+i);
        treeitem.appendChild(treerow);

        treechildren.appendChild(treeitem);
    }

    //Determine the XY possition of the mouse
    var searchGridXYCallback=function(e){
        var event=e;
        var posx=gridList.boxObject.screenX;
        var posy=gridList.boxObject.y ;
        posx +=  e.clientX;
        posy =  e.clientY+posy/2;
        if(e.button==2){
            document.getElementById('clipmenu-searchresults').showPopup(document.documentElement, posx, posy, "bottomleft", "topleft");
        }
    }
    gridList.addEventListener("mousedown", searchGridXYCallback, false);

    //So we dont have to requery
    gLastSearchXMLData=xmldata;
}

/**
 * Initialize the watchdog
 */
function initWatchDog(){

    //Initalize the timer
    Footbar.Watchdog.initTimer();
    Footbar.Watchdog.runUpdate();


    //Load the WatchDog SetName
    var url="chrome://footbar/content/xml/watchdog-sets-data.xml";
    var httpRequest;
    httpRequest = new XMLHttpRequest();
    httpRequest.overrideMimeType('text/xml');

    httpRequest.open('GET', url, false);
    httpRequest.send(null);

    var xmldata = httpRequest.responseXML;

    //Create Tree out of XML

    var gridList=document.getElementById( 'footbar-set-tree-watchdog' );
    var	treechildren = gridList.getElementsByTagName("treechildren")[0];
    var root = xmldata.getElementsByTagName("root")[0];
    var items = root.getElementsByTagName("set");

    for (var i=0;i<items.length;i++){
        var itemrow=items[i];
        var title=itemrow.getAttribute("name");
        var setKey=itemrow.getAttribute("key");
        var keywords=itemrow.getElementsByTagName("keywords")[0];
        keywords=keywords.getElementsByTagName("pair");

        var	treeitem = document.createElement("treeitem");
        treeitem.setAttribute("container", "true");
        treeitem.setAttribute("open", "false");
        treeitem.setAttribute("setKey", setKey);
        treeitem.setAttribute("isSet", true);


        var	treerow = document.createElement("treerow");
        treerow.setAttribute("id",  "setname-treerow-"+i);

        var label_title= document.createElement("treecell");
        label_title.setAttribute("label",  title);

        var  sub_treechildren = document.createElement("treechildren");
        for(var k=0;k<keywords.length;k++){
            var dataObject;

            var nodeLabel=keywords[k].getAttribute("value");
            var nodeKey=keywords[k].getAttribute("key");
            dataObject={
                label:nodeLabel,
                key:nodeKey
            };
            sub_treechildren.appendChild( Footbar.TreeUtil.cellNode(dataObject) );
        }
        treerow.appendChild(label_title);
        treeitem.appendChild(treerow);
        treeitem.appendChild(sub_treechildren);
        treechildren.appendChild(treeitem);

    }

}


function watchdogNodeSelect(){
    var tree=document.getElementById('footbar-set-tree-watchdog');
    var currentitem = tree.treeBoxObject.view.getItemAtIndex(tree.currentIndex);
    if(!currentitem.hasAttribute("isSet")){
        return;
    }
    var childElements=currentitem.getElementsByTagName("treechildren")[0];
    var rootCell=currentitem.getElementsByTagName("treecell")[0];
    childElements=childElements.getElementsByTagName("treecell");
    var items=[];
    for(var i=0;i<childElements.length;i++){
        items[items.length]=childElements[i].getAttribute("key");
    }
    markCheckboxesForSelection(document.getElementById('grid-tags-watchdog'), items);


    //SetName
    var setName=document.getElementById('footbar-watchdog-setname');
    setName.value=rootCell.getAttribute("label");
    gSetKey=currentitem.getAttribute("setKey");

    var saveButton=document.getElementById('footbar-watchdog-setname-savebutton');
    saveButton.setAttribute("label","  Update")
}





function editSnippet(){
    var snippet=searchResults[document.getElementById('search-list-tree').currentIndex];
    Footbar.TabWatcher.setFocus('footbar-footer-tabs', 1);

    var tru_snippet_title=document.getElementById('tru_snippet_title');
    tru_snippet_title.value=snippet.title;

    var tru_snippet_description=document.getElementById('tru_snippet_description');
    tru_snippet_description.value=snippet.description;

    var tru_snippet_code=document.getElementById('tru_snippet_code');
    tru_snippet_code.value=snippet.code;

    var saveButton=document.getElementById('footbar-button-saveSnippet');
    saveButton.setAttribute("label","  Update");
    saveButton.setAttribute("mode",2);

    var kwdata=snippet.keywords.data;

    var dataItems=function(){
        var items=[];
        for(var i=0;i<kwdata.length;i++){
            items[items.length]=kwdata[i].key;
        }
        return items;
    }();

    //Select appropriate checkboxes
    markCheckboxesForSelection(document.getElementById('grid-tags-add'), dataItems);
}


/**
 * make checkboxes checked if the value matches passed in array value list
 * Checkboxes must be inside a container
 * @param {Object} container
 * @param {Object} matchedValueArray
 */
function markCheckboxesForSelection(container, matchedValueArray){
    var checkBoxes=container.getElementsByTagName('checkbox');
    if(checkBoxes==null){
        alert("Can't find :"+targetCheckboxName );
        return;
    }
    for(var i=0;i<checkBoxes.length;i++){
        var box=checkBoxes[i];
        box.checked=false;//uncheck by default
        for(var j=0;j<matchedValueArray.length;j++){
            if(box.getAttribute("value")==matchedValueArray[j]){
                box.checked=true;
            }
        }
    }
}

function changeHighlighter(lang){
    searchTreeSelected(lang);
}

function searchTreeSelected(lang){
    var tree = document.getElementById('search-list-tree');
    var tabViewState=document.getElementById('footbar-tabView').checked;

    if(tree.currentIndex==-1){
        return ;
    }

    var treeIndex=(gCurrentPageIndex*gRecordsPerPage)-gRecordsPerPage+tree.currentIndex;

    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
            .getService(Components.interfaces.nsIWindowMediator);
    var browserWindow = wm.getMostRecentWindow("navigator:browser");
    var tabDocument = browserWindow.content.document;
    var unsafeWindow=browserWindow.content.window.wrappedJSObject;
    var tabDOM={document:tabDocument,window:unsafeWindow};

    if(lang==null){
        lang=searchResults[treeIndex].language+":nogutter:nocontrols";
    }else{
        lang=lang+":nogutter:nocontrols";
    }
    //mark the current row as read
    var selection = tree.contentView.getItemAtIndex(tree.currentIndex);
    var cells=selection.getElementsByTagName('treecell');
    for(var k=0;k<cells.length;k++){
        cells[k].setAttribute("properties","read");
    }

    //selection.firstChild.firstChild.setAttribute("properties","read");
    searchResults[treeIndex].read=true;
    var colorizeCode=function(object, showHeader){
        try{
            object.document.getElementById('footbar-code').value=searchResults[treeIndex].code;
            object.document.getElementById('footbar-code').className=lang;

            if(showHeader){
                object.document.getElementById('trucoder-header').style.display="";
                object.document.getElementById('trucoder-header-title').innerHTML=searchResults[treeIndex].title;
                object.document.getElementById('trucoder-header-description').innerHTML=searchResults[treeIndex].description;

            }else{
                object.document.getElementById('trucoder-header').style.display="none";
            }

            object.window.colorize();
        }catch(e){
            //alert(e);
        }
    }
    if(tabViewState){
        //Ref: http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Getting_access_to_the_Browser
        var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                .getInterface(Components.interfaces.nsIWebNavigation)
                .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
                .rootTreeItem
                .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
                .getInterface(Components.interfaces.nsIDOMWindow);


        var gBrowser=mainWindow.getBrowser();

        var num = gBrowser.browsers.length;
        var found=false;
        for (var i = 0; i < num; i++) {
            var b = gBrowser.getBrowserAtIndex(i);
            try {
                if(b.currentURI.spec==tabURI){
                    gBrowser.selectedTab = b;
                    b.focus();
                    gBrowser.mTabContainer.selectedIndex=i;
                    // Focus *this* browser
                    gBrowser.focus();
                    found=true;
                    break;
                }
            } catch(e) {
                alert(e);
            }
        }

        colorizeCode(tabDOM, true);

    }else{
        colorizeCode(new codeFrame(0), false);
        colorizeCode(new codeFrame(1), false);
    }

    //Set the Decsription
    document.getElementById('footbar-iDescription').value=searchResults[treeIndex].description;
    document.getElementById('footbar-iDescription-split').value=searchResults[treeIndex].description;

}

/**
 * Helper Object to access the code I frame
 */
var codeFrame=function(containerID){
    //containerID 0= Root 1= Split
    var container;
    if(containerID==null){
        container='footbar-iSource';
    }else{
        switch(containerID){
            case 0:{
                container='footbar-iSource';
                break;
            }
            case 1:{
                container='footbar-iSource-split';
                break
            }
        }
    }
    var rootFrame=document.getElementById(container);
    var _doc;
    var _win;
    _doc = rootFrame.contentDocument || rootFrame.contentWindow.document;
    _doc = rootFrame.contentWindow.document;
    _win= rootFrame.contentWindow.window
    return{
        document:_doc,
        window:_win
    }
};

function parseXML2Keywords(){
    Trucoder.GridUtil.parseXML2KeywordsForGrid('grid-tags-add');
    Trucoder.GridUtil.parseXML2KeywordsForGrid('grid-tags-search');
    //parseXML2KeywordsForGrid('grid-tags-watchdog');
}

function doSaveSnippet(){
    var snippet={};
    var tru_snippet_title=document.getElementById('tru_snippet_title');
    snippet.title=tru_snippet_title.value;

    var tru_snippet_description=document.getElementById('tru_snippet_description');
    snippet.description=tru_snippet_description.value;

    var tru_snippet_code=document.getElementById('tru_snippet_code');
    snippet.code=tru_snippet_code.value;

    var tru_snippet_customKeywords=document.getElementById('tru_snippet_customtags');
    snippet.customKeywords=tru_snippet_customKeywords.value;

    var checkBoxes=document.getElementById('grid-tags-add')
    var checkBoxes=checkBoxes.getElementsByTagName('checkbox');
    var kwdata=[];
    for(var k=0;k<checkBoxes.length;k++){
        var box=checkBoxes[k];
        if(box.checked){
            var dataObject={
                label:box.getAttribute("label"),
                key:box.getAttribute("value")
            };
            kwdata[kwdata.length]=dataObject;
        }
    }
    snippet.keywords=kwdata;

    //Retrive language
    var tru_snippet_language=document.getElementById('tru_snippet_language');
    var selectedItemLanguage = tru_snippet_language.selectedItem;
    snippet.language=selectedItemLanguage.value;



    var saveButton=document.getElementById('footbar-button-saveSnippet');
    var mode=saveButton.getAttribute("mode");
    if(mode==1){
        if(Footbar.Plugins.getActiveEngine().validateBeforeSave( snippet )){
            Footbar.Plugins.getActiveEngine().saveSnippet( snippet );
        }
    }else if(mode==2){

        if(Footbar.Plugins.getActiveEngine().validateBeforeUpdate( snippet )){
            var tree = document.getElementById('search-list-tree');
            var treeIndex=(gCurrentPageIndex*gRecordsPerPage)-gRecordsPerPage+tree.currentIndex;
            snippet.uid=searchResults[treeIndex].uid;
            Footbar.Plugins.getActiveEngine().updateSnippet( snippet );
        }
    }
}


/*
function saveSnippet(){
      httpRequest = new XMLHttpRequest();
      httpRequest.overrideMimeType('text/xml');
      httpRequest.open('POST', url, true);
      httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      httpRequest.setRequestHeader("Content-length", parameters.length);
      httpRequest.setRequestHeader("Connection", "close");

      httpRequest.onreadystatechange = function() {
     try{
        if (httpRequest.readyState == 4) {
              if (httpRequest.status == 200) {
                alert(httpRequest.responseText);
               } else {
                      alert('There was a problem with the request.');
                }
            }
     }
     catch( e ) {
            alert('Caught Exception: ' + e.description);
          }
    };

      var parameters = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
                      "&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
      httpRequest.send(parameters);

}
*/

function setDeck(index)
{
    document.getElementById("my-deck").setAttribute("selectedIndex",index);
}


var configPanels=[];
configPanels['login']={
    state:1
};

configPanels['watchdog']={
    state:1
};

configPanels['sync']={
    state:1
};
/**
 * Simple function to toggle config panels on.off
 * @param {Object} panelName
 */
function toggleConfigPanel(panelName){
    var target;
    var elem;

    for(x in configPanels){
        elem=document.getElementById('trucoder-engine-config-'+x);
        if(elem==null)continue;

        if(x==panelName){
            target=elem;
        }else{
            configPanels[x].state=1;
            elem.style.display="none";
        }
    }
    var panel=configPanels[panelName];
    target.style.display=(panel.state==1)?"":"none";
    panel.state=(panel.state==1)?0:1;
}

/**
 * Perform initalization for the sidebar
 */
function init(){

    Footbar.Plugins.init();
    gFoundEngines=Footbar.Plugins.getEngines();

    var engine=null;
    var isFirstEngine=true;
    while((engine=gFoundEngines.pop())!=null){
        var radioContainer=document.getElementById('footbar-available-engine');
        //alert(engine);
        var metadata=engine.getMetadata();
        var radio=document.createElement('radio');
        radio.setAttribute("id", "0");
        radio.setAttribute("label", metadata.title);

        var radioEvent = {
            handleEvent: function(e) {

                Footbar.Plugins.setActiveEngine( this.object );
                var activeEngine=Footbar.Plugins.getActiveEngine(  );
                var meta=activeEngine.getMetadata();

                var login=document.getElementById('activeengine-meta-loginRequired');
                login.value=meta.loginRequired;

                var watchdog=document.getElementById('activeengine-meta-watchDogEnabled');
                watchdog.value=meta.watchDogEnabled;

                var www=document.getElementById('activeengine-meta-www');
                www.value=meta.www;

                var author=document.getElementById('activeengine-meta-author');
                author.value=meta.author;

                var version=document.getElementById('activeengine-meta-version');
                version.value=meta.version;
            },

            object:engine
        }
        radio.addEventListener("click", radioEvent, true);

        radioContainer.appendChild(radio);

        if(isFirstEngine){
            isFirstEngine=false;
            radio.setAttribute("selected", true);

            //@ref: http://developer.mozilla.org/en/docs/DOM:document.createEvent#Example
            //Simulate Click on first event so it populates all the metadata etc..
            var evt=document.createEvent("MouseEvents");
            evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            radio.dispatchEvent(evt);
        }

        var label=document.createElement('label');
        label.setAttribute("value", metadata.description+"\n");
        radioContainer.appendChild(label);
    }

    var activeEngine=Footbar.Plugins.getActiveEngine(  );
    var meta=activeEngine.getMetadata();

    if(meta.loginRequired){
        //alert("Prompting for login");
    }

    //Disable watchdog tab if the plugin does not support it
    if(!meta.watchDogEnabled){
        var CustomTab_DisabledWatchDog = {
            index:3,
            preventDefault:true,
            panelName:'CustomTab_DisabledWatchDog',
            onClick:function(){
                /**
                 * @todo:Fix Watchdog
                 */
                return;
                //Set focus back to the previously selected tab.
                var indexActive=Footbar.TabWatcher.getLastActiveTab('footbar-footer-tabs');
                if(indexActive=='undefined'){
                    indexActive=0;
                }

                Footbar.TabWatcher.setFocus('footbar-footer-tabs',indexActive );
                alert("WatchDog is not supported by this plugin. ");
            }
        }
        Footbar.TabWatcher.bindSingleTab('footbar-footer-tabs', CustomTab_DisabledWatchDog);
    }

    //Bind the FreeText and Tag Based Search Tabs
    var CustomTab_SearchFreeText= {
        index:0,
        preventDefault:true,
        panelName:'CustomTab_SearchFreeText',
        onClick:function(){
            var deck_1=document.getElementById('trucoder-panels-search-tabs-deck-1');
            deck_1.style.visibility="";

            var deck_2=document.getElementById('trucoder-panels-search-tabs-deck-2');
            deck_2.style.visibility="";
        }
    }
    //trucoder-panels-search-tabs-deck
    Footbar.TabWatcher.bindSingleTab('trucoder-panels-search-tabs', CustomTab_SearchFreeText);



    //Bind the FreeText and Tag Based Search Tabs
    var CustomTab_SearchTagGrid = {
        index:1,
        preventDefault:true,
        panelName:'CustomTab_SearchTagGrid',
        onClick:function(){
            var deck_1=document.getElementById('trucoder-panels-search-tabs-deck-1');
            deck_1.style.visibility="";

            var deck_2=document.getElementById('trucoder-panels-search-tabs-deck-2');
            deck_2.style.visibility="";
        }
    }
    //trucoder-panels-search-tabs-deck
    Footbar.TabWatcher.bindSingleTab('trucoder-panels-search-tabs', CustomTab_SearchTagGrid);


    //nsPreferences.setBoolPref("scrapbook.note.linefeed", document.getElementById("sbNoteToolbarL").getAttribute("checked") ? true : false);

    //Bind the RSSConfig to save data on blur
    var CustomTab_RSSConfig = {
        index:2,
        preventDefault:true,
        panelName:'CustomTab_RSSConfig',
        onClick:function(e){
            dump("\n > ***************** onClick "+e.currentTarget.tagName);
            dump("\n       >  isSelected = "+e.currentTarget.getAttribute('selected'));

        },
        onBlur:function(e){
            var elem=e.target;
            dump("\n >onBlur "+e.currentTarget.tagName);
            /*
            while(elem.parentNode.id!='trucoder-panels-srv-tabs'){
                dump("\n >> "+e.type )
                for(x in e){
                    //dump("\n       - "+x)
                }
                elem=elem.parentNode;
            }
            */
        }
    }
    Footbar.TabWatcher.bindSingleTab('trucoder-panels-srv-tabs', CustomTab_RSSConfig);


    var searchBox=document.getElementById('footbar-search-box');
    //Detect Enter Press then submit the data
    searchBox.addEventListener("keypress", function(e){
        if(e.keyCode==13/*Enter*/){
            doSearchQuery();
        }
    }, true);

    //Reset text on Focus
    searchBox.addEventListener("focus", function(e){
        this.value="";
    }, true);

    Footbar.TabWatcher.initalize();

    var CustomTabs=[];
    var CustomTab_0 = {
        index:0,
        panelName:'footbar-deck-viewcode',
        onClick:function(){
            //alert("Clicked The tab 0");
            //Do noting right now just show the tab
        }
    }

    var CustomTab_1 = {
        index:1,
        panelName:'footbar-deck-viewdesc',
        onClick:function(){
            // alert("Clicked The tab 1");
            //Do noting right now just show the tab
        }
    }

    var CustomTab_2 = {
        index:2,
        panelName:'footbar-deck-viewmixed',
        onClick:function(){
            //Do noting right now just show the tab
        }
    }

    CustomTabs[CustomTabs.length]=CustomTab_0;
    CustomTabs[CustomTabs.length]=CustomTab_1;
    CustomTabs[CustomTabs.length]=CustomTab_2;

    Footbar.TabWatcher.bindTabs('footbar-view-tabs', CustomTabs);

    //Setup Footer tabs
    var CustomTabs=[];
    var CustomTab_dummy = {
        index:1,
        panelName:'dummyTab',
        onClick:function(){
            //Do noting right now just show the tab
        }
    }
    var CustomTab_AddEdit = {
        index:1,
        panelName:'CustomTab_AddEdit',
        onClick:function(){
            var tru_snippet_title=document.getElementById('tru_snippet_title');
            tru_snippet_title.value="";

            var tru_snippet_description=document.getElementById('tru_snippet_description');
            tru_snippet_description.value="";

            var tru_snippet_code=document.getElementById('tru_snippet_code');
            tru_snippet_code.value="";

            var tru_snippet_customKeywords=document.getElementById('tru_snippet_customtags');
            tru_snippet_customKeywords.value="";

            var checkBoxes=document.getElementById('grid-tags-add')
            var checkBoxes=checkBoxes.getElementsByTagName('checkbox');
            for(var k=0;k<checkBoxes.length;k++){
                var box=checkBoxes[k];
                box.checked=false;
            }
            var saveButton=document.getElementById('footbar-button-saveSnippet');
            saveButton.label="  Save";
            saveButton.setAttribute("mode", 1);
        }
    }

    CustomTabs[CustomTabs.length]=CustomTab_dummy;
    CustomTabs[CustomTabs.length]=CustomTab_AddEdit;
    CustomTabs[CustomTabs.length]=CustomTab_dummy;
    CustomTabs[CustomTabs.length]=CustomTab_dummy;
    CustomTabs[CustomTabs.length]=CustomTab_dummy;

    Footbar.TabWatcher.bindTabs('footbar-footer-tabs', CustomTabs);


    //Ref: http://developer.mozilla.org/en/docs/Code_snippets:Tabbed_browser#Getting_access_to_the_Browser
    var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
            .getInterface(Components.interfaces.nsIWebNavigation)
            .QueryInterface(Components.interfaces.nsIDocShellTreeItem)
            .rootTreeItem
            .QueryInterface(Components.interfaces.nsIInterfaceRequestor)
            .getInterface(Components.interfaces.nsIDOMWindow);

    var gBrowser=mainWindow.getBrowser();

    //var evt=document.createEvent("MouseEvents");
    //evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    //tabViewButton.dispatchEvent(evt);

    //Detect close of the Source Tab and make the source appear in the box
    gBrowser.addEventListener("TabClose", function(e){
        //@ref: http://developer.mozilla.org/en/docs/DOM:document.createEvent#Example
        //Simulate Click on first event so it populates all the metadata etc..

        var tabViewButton=document.getElementById('footbar-tabView');
        var codeOverlayContainer=document.getElementById('footbar-code-box');
        var codeContainer=document.getElementById('footbar-code-box-container');

        codeOverlayContainer.setAttribute("flex","1");
        codeContainer.style.display="";
        tabViewButton.image="/skin/tab_new.png";
        tabViewButton.checked=true;
    }, false);

}

// add on load event handler
window.addEventListener("load", function(){
    init();
    //initWatchDog();
    parseXML2Keywords();
    Footbar.Srv.init();

    //Initialize team speak service
    Footbar.TeamSpeakService.init();
}, true);


function renderDataSetToTab(){
    var     templateData='';
    templateData+='\n<row uid = "{uid}">';
    templateData+='\n<title>{title}</title>';
    templateData+='\n<keywords>{keywords}</keywords> ';
    templateData+='\n<description>{description}</description>     ';
    templateData+='\n<code language = "{language}"><![CDATA[{code}]]></code> ';
    templateData+='\n</row>';

    /*
   obj={
       title:title.textContent,
       keywords:{label:keywordsLabel,data:keywordData},
       description:description.textContent,
       code:code.textContent,
       language:code.getAttribute("language"),
       read:false,
       uid:itemrow.getAttribute("uid")
   };
    */

    var compiled="";
    for(var i=0;i<searchResults.length;i++){
        var obj={}
        var molder=new Footbar.FireTag();
        molder.setTemplate( templateData );
        obj =  searchResults[i];

        var keyword='';
        for(var k=0;k<obj.keywords.data.length;k++){
            keyword+='<pair value = "'+obj.keywords.data[k].value+'" key = "'+obj.keywords.data[k].key+'"/>'
        }
        molder.addVariable('keywords', keyword);

        molder.addVariable('uid', obj.uid);
        molder.addVariable('title', obj.title);
        molder.addVariable('description', obj.description);
        molder.addVariable('language', obj.language);
        molder.addVariable('code', obj.code);
        var output=molder.run();
        compiled+=output;
    }

    var output="";

    output+='<?xml version="1.0" encoding="iso-8859-1"?>';
    output+='<root>';
    output+=compiled;
    output+='</root>';

    var templatePathOut=Footbar.Util.findPluginPath(true)+"chrome\\content\\xml\\display-dataset.xml";
    Footbar.Util.writeFileData(templatePathOut, output);

    var executeURI=DisplayDatasetURI;
    var gBrowser=Footbar.Util.getBrowser();
    //Check if the URI is open
    if(Footbar.Util.isTabURIOpen( executeURI )){
        Footbar.Util.focusTab( executeURI );
    }else{
        // Add tab, then make active
        gBrowser.selectedTab = gBrowser.addTab( executeURI );
        gBrowser.focus();
    }
    //Grab DOM and call execute to apply XSL stylesheet
    var domSet=Footbar.Util.getTabDOM( executeURI );
    //call execute method in the open Tab
    //this will reload the xml and xls files

    //Somehow the attacheEventListner is not working so we are simply retrying to call the function till we suceed
    var inter=0;
    inter = setInterval (function(){
        try{
            domSet.window.execute("single");
            clearInterval (inter);
        }catch(e){ //Suppress all errors
            //alert(e);
            //dump(e);
        }
    },50);
}